//
//  GouWuCheMainViewController.m
//  ShangChengMoBan
//
//  Created by 张铁军 on 16/8/13.
//  Copyright © 2016年 ping. All rights reserved.
//

#import "GouWuCheMainViewController.h"
#import "GoTableViewCell.h"
#import <RWUIControls/RWUIControls.h>
#import "GWJ_Content.h"
#import "GoodsAttrMapper.h"
#import "JieSuanViewController.h"
#import "GoodsAttrMapper.h"
#import "DD_fotherModel.h"

@interface GouWuCheMainViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *all;
- (IBAction)complete:(id)sender;
- (IBAction)account:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *complete;
@property (weak, nonatomic) IBOutlet UIButton *completeImage;
@end

@implementation GouWuCheMainViewController
{
    GWJ_Content * _GWC_content;
    NSMutableArray *_shuLabAry1;
    NSArray * _goodsAtt;
    UITableView * goTable;
    float prizes;//总价钱
    float shuXingMoney;
    NSString * _velue ;
    UIView * _view,*_viewNo;
    NSMutableArray * _prizeArr;
    NSMutableArray * _velueArr;
  }
- (void)viewDidLoad {
    [super viewDidLoad];
    _prizeArr = [[NSMutableArray alloc]init];
    _velueArr = [[NSMutableArray alloc]init];
    _velue = [[NSMutableString alloc]initWithString:@""];
    prizes = 0.00;
    _complete.selected=NO;
    //设置标题
    [self drawNavWithTitle:@"购物车"];
    self.view.backgroundColor = [UIColor colorWithHue:0.67 saturation:0.02 brightness:0.96 alpha:1.00];
    if (_timp == 1) {
        [self drawBackButton];
    }
    [self tableView];
    [self creatFontView];//添加底部视图
     _all.text = [NSString stringWithFormat:@"总价:¥%.2f",prizes];
 }
-(void)viewWillAppear:(BOOL)animated{
     [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(take) name:@"未登录" object:nil];
    if (![_a isEqualToString:@"1"]) {
        goTable.hidden = NO;
        _view.hidden = NO;
        self.b = 1;
     if ([self jianCeLogin]) {
    [self requestData];
     }
    }else{
        goTable.hidden = YES;
        _view.hidden = YES;
    }
    [_completeImage setImage:[UIImage imageNamed:@"圆圈"] forState:UIControlStateNormal];
    _completeImage.selected = NO;
    
 }
-(void)take{
    _a = @"1";
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    _a = @"0";
}
-(void)tableView{
    //设置TableView
    if (_timp == 1) {
         goTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight-114 ) ];
    }else{
     goTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, KScreenWidth, KScreenHeight-164 ) ];
    }
    goTable.separatorStyle = UITableViewCellSelectionStyleNone;
    goTable.delegate=self;
    goTable.dataSource=self;
    goTable.backgroundColor = [UIColor colorWithHue:0.67 saturation:0.02 brightness:0.96 alpha:1.00];
    [self.view addSubview:goTable];
    [goTable registerClass:[GoTableViewCell class] forCellReuseIdentifier:@"cell"];
    goTable.rowHeight=152;
    //去除自适应
    self.automaticallyAdjustsScrollViewInsets = NO;
}
-(void)requestData{
    _shuLabAry1 = [NSMutableArray array];
     [TCUtils showLoadingWithView:self.view];
   
        shuXingMoney = 0.00;
        [NetWorking NEWjieKouQingQiu:GWC_myCart ANDIP:IP And:@{@"userName":[self defaultLoadUserName]} anBlock:^(NSDictionary *dic, NSError *error) {
             [TCUtils hiddonLoadingWithView:self.view];
            if (!error) {
                if ([dic[Code] intValue] == 200) {
                    NSArray * data = dic[Response];
                    
                    [data enumerateObjectsUsingBlock:^(id   obj, NSUInteger idx, BOOL *  stop) {
                        _GWC_content = [GWJ_Content objectFromDictionary:obj];
                        [_shuLabAry1 addObject:_GWC_content];
                        _goodsAtt = _GWC_content.goodsAttrMapper;
                        [_goodsAtt enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            GoodsAttrMapper *goodsAttrMapper = obj;
                            shuXingMoney += [goodsAttrMapper.attrPrice floatValue];
                            _velue = [_velue stringByAppendingString:[NSString stringWithFormat:@"%@ ",goodsAttrMapper.attrValue]];
                        }];
                        [_prizeArr addObject:[NSString stringWithFormat:@"%f",shuXingMoney]];
                        [_velueArr addObject:_velue];
                        _velue = @"";
                        shuXingMoney = 0.00;
                    }];
                    if (_shuLabAry1.count==0) {
                        [self noShop];
                    }else{
                        [_viewNo removeFromSuperview];
                    }

                    [goTable reloadData];
                    _view.hidden = NO;
                    [self zongJia];
                    if (data.count == 0) {
                        [_shuLabAry1 removeAllObjects];
                        //删除商品将底部试图隐藏
                        _view.hidden = YES;
                    }
                }
            }
        }];
    
 }
-(void)noShop{
    [_viewNo removeFromSuperview];
    _viewNo = [[[NSBundle mainBundle]loadNibNamed:@"GWC_NoShop" owner:self options:nil] lastObject];
    _viewNo.frame = CGRectMake(0, 100, KScreenWidth, 127);
    _viewNo.backgroundColor = [UIColor colorWithHue:0.67 saturation:0.02 brightness:0.96 alpha:1.00];
    [goTable addSubview:_viewNo];
}
#pragma mark 底部视图
-(UIView *)creatFontView{
    _view = [[[NSBundle mainBundle]loadNibNamed:@"Account" owner:self options:nil] firstObject];
     //没有商品将底部试图隐藏
    _view.hidden = YES;
    if (_timp == 1) {
         _view.frame=CGRectMake(0, KScreenHeight-50, KScreenWidth, 50);
    }else{
     _view.frame=CGRectMake(0, KScreenHeight-100, KScreenWidth, 50);
    }
    [self.view addSubview:_view];
    return _view;
}

#pragma mark 行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _shuLabAry1.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    _GWC_content = _shuLabAry1[indexPath.row];
    shuXingMoney = [_prizeArr[indexPath.row] floatValue];//属性价钱
    _velue = _velueArr[indexPath.row];//属性
    GoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.prize.text = [NSString stringWithFormat:@"¥%.2f",shuXingMoney + [_GWC_content.goodsmapper.shopPrice floatValue]];
    cell.style.text = _velue;
    cell.content.text = _GWC_content.goodsName;
    [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_GWC_content.goodsmapper.goodsThumb]]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.add addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    cell.add.tag = indexPath.row;
    cell.cut.tag = indexPath.row;
    cell.remove.tag = indexPath.row;
    cell.choice2.tag = indexPath.row+100;
    [cell.choice2 addTarget:self action:@selector(choice2:) forControlEvents:UIControlEventTouchUpInside];
    [cell.remove addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
    [cell.cut addTarget:self action:@selector(cut:) forControlEvents:UIControlEventTouchUpInside];
    //商品数量
     cell.num.text = [NSString stringWithFormat:@"%@",_GWC_content.goodsNumber] ;
    //小计
     cell.small.text = [NSString stringWithFormat:@"小计:¥%.2f",[_GWC_content.goodsNumber floatValue]*(shuXingMoney + [_GWC_content.goodsmapper.shopPrice floatValue])];
    //判断当前选中状态
    BOOL a = [_GWC_content.recType boolValue];
    if (a) {
        [cell.choice2 setImage:[UIImage imageNamed:@"对勾"] forState:UIControlStateNormal];
        cell.small.hidden=NO;
    }else {
    [cell.choice2 setImage:[UIImage imageNamed:@"圆圈"] forState:UIControlStateNormal];
         cell.small.hidden=YES;
    }
      return cell;
}
#pragma mark 点击进入商品详情页
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    
  }

#pragma mark 加
-(void)add:(UIButton *)button{
    _GWC_content = _shuLabAry1[button.tag];
    int goodsNumber = [_GWC_content.goodsNumber intValue];
        goodsNumber++;
    _GWC_content.goodsNumber = [NSString stringWithFormat:@"%i",goodsNumber];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[self defaultLoadUserName] forKey:@"userName"];
    [dic setObject:_GWC_content.recId forKey:@"recId"];
    [dic setObject:@(goodsNumber) forKey:@"goodsNumber"];
    [NetWorking NEWjieKouQingQiu:GWC_edit ANDIP:IP And:dic anBlock:^(NSDictionary *dic, NSError *error) {
        if (!error) {
            if ([dic[Code] intValue] == 200) {
                 [goTable reloadData];
            }
        }
    }];
    [self zongJia];//总价
    }
#pragma mark 减
-(void)cut:(UIButton *)sender{
     _GWC_content = _shuLabAry1[sender.tag];
    int goodsNumber = [_GWC_content.goodsNumber intValue];
    if (goodsNumber>1) {
        goodsNumber--;
    _GWC_content.goodsNumber = [NSString stringWithFormat:@"%i",goodsNumber];
    }
   
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[self defaultLoadUserName] forKey:@"userName"];
    [dic setObject:_GWC_content.recId forKey:@"recId"];
    [dic setObject:@(goodsNumber) forKey:@"goodsNumber"];
    [NetWorking NEWjieKouQingQiu:GWC_edit ANDIP:IP And:dic anBlock:^(NSDictionary *dic, NSError *error) {
        if (!error) {
            if ([dic[Code] intValue] == 200) {
                [goTable reloadData];
          }
        }
    }];
    [self zongJia];//总价
 }
#pragma mark 单选
-(void)choice2:(UIButton *)button{
    _GWC_content = _shuLabAry1[button.tag-100];
    NSString *a = _GWC_content.recType;
    BOOL b = [a boolValue];
    b = !b;
    _GWC_content.recType = [NSString stringWithFormat:@"%d",b];
    [self style];//是否全选状态
    [self zongJia];//总价
    [goTable reloadData];
}
#pragma mark 判断是否为全选状态
-(void)style{
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    [_shuLabAry1 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * stop) {
        _GWC_content = obj;
        if (![_GWC_content.recType boolValue]) {
            [arr addObject:_GWC_content];
        }
    }];
    if (arr.count == 0 ) {
        [_completeImage setImage:[UIImage imageNamed:@"对勾"] forState:UIControlStateNormal];
        _completeImage.selected = YES;
    }
    if (arr.count > 0) {
        [_completeImage setImage:[UIImage imageNamed:@"圆圈"] forState:UIControlStateNormal];
        _completeImage.selected = NO;
    }
}
#pragma mark 用于计算总价
-(void)zongJia{
    prizes = 0.00;
    for (int i = 0; i<_shuLabAry1.count; i++) {
        _GWC_content = _shuLabAry1[i];
        if ([_GWC_content.recType boolValue]) {
            prizes += ([_GWC_content.goodsmapper.shopPrice floatValue]+[_prizeArr[i] floatValue]) *[_GWC_content.goodsNumber floatValue];
        }
    }
    _all.text = [NSString stringWithFormat:@"总价:¥%.2f",prizes];
}
#pragma mark 全选
- (IBAction)complete:(id)sender {
      _completeImage.selected = !_completeImage.selected;
    if (_completeImage.selected) {
        [_completeImage setImage:[UIImage imageNamed:@"对勾"] forState:UIControlStateNormal];
        [_shuLabAry1 enumerateObjectsUsingBlock:^(id  obj, NSUInteger idx, BOOL * _Nonnull stop) {
      _GWC_content = obj;
       _GWC_content.recType = [NSString stringWithFormat:@"%d",YES];
        }];
        [_complete setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    }else{
        [_completeImage setImage:[UIImage imageNamed:@"圆圈"] forState:UIControlStateNormal];
        [_shuLabAry1 enumerateObjectsUsingBlock:^(id  obj, NSUInteger idx, BOOL *  stop) {
            _GWC_content= obj;
            _GWC_content.recType = [NSString stringWithFormat:@"%d",NO];
        }];
    }
    [self zongJia];//总价
    [goTable reloadData];
}
#pragma mark 删除
-(void)remove:(UIButton *)button{
      [TCUtils showAlertViewWithTitle:@"提醒" message:@"你确定要删除这个宝贝吗?" delegate:self cancel:@"取消" other:@"确定" tag:(int)button.tag];
   }
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        _GWC_content = _shuLabAry1[alertView.tag];
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:[self defaultLoadUserName] forKey:@"userName"];
        [dic setObject:_GWC_content.recId forKey:@"recId"];
        
        [NetWorking NEWjieKouQingQiu:GWC_removeGoods ANDIP:IP And:dic anBlock:^(NSDictionary *dic, NSError *error) {
            if (!error) {
                if ([dic[Code] intValue] == 200) {
                    [[iToast makeText:@"  删除成功  "] show];
                    [_shuLabAry1 removeObjectAtIndex:alertView.tag];
                    if (_shuLabAry1.count==0) {
                        _view.hidden = YES;
                        [self noShop];
                    }
                    [self style];//是否全选状态
                    [self zongJia];//总价
                    [goTable reloadData];
                }
            }
        }];
    }
}

#pragma mark 结算
- (IBAction)account:(id)sender {
  
    NSMutableArray * arr = [[NSMutableArray alloc]init];
    [_shuLabAry1 enumerateObjectsUsingBlock:^(id  obj, NSUInteger idx, BOOL * stop) {
        _GWC_content = obj;
        if ([_GWC_content.recType boolValue]) {
            NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            
            [dic setObject:[NSString stringWithFormat:@"%@",_GWC_content.recId] forKey:@"gouWuCheId"];//商品ID
            [dic setObject:[NSString stringWithFormat:@"%@",_GWC_content.goodsNumber] forKey:@"goodsNumber"];//商品数量
            [dic setObject:[NSString stringWithFormat:@"%@",_GWC_content.goodsId] forKey:@"goodsId"];
            //[dic setObject:_GWC_content.recId forKey:@"isGift"];
            NSMutableArray * attreAry = [[NSMutableArray alloc]init];
            for (GoodsAttrMapper * peiZhi in _GWC_content.goodsAttrMapper) {
                [attreAry addObject:[NSString stringWithFormat:@"%@",peiZhi.goodsAttrId]];
            }
            [dic setObject:attreAry forKey:@"goodsAttrId"];//商品属性
            [arr addObject:dic];
        }
        
    }];
    
    if (arr.count > 0) {
        
        NSMutableDictionary *requestDic = [[NSMutableDictionary alloc]init];
        [requestDic setObject:[self defaultLoadUserName] forKey:@"userName"];
       
        NSString *jsonstr = [JsonString jsonStringWithArray:arr];
        [requestDic setObject:jsonstr forKey:@"p"];
        

        [NetWorking NEWjieKouQingQiu:GWC_yuXiaDan ANDIP:IP And:requestDic anBlock:^(NSDictionary *dic, NSError *error) {
            if (!error) {
                if ([dic[Code] intValue] == 200) {
                    
                DD_fotherModel *yudingDan = [DD_fotherModel objectFromDictionary:[dic objectForKey:Response]];
                 
                    [[iToast makeText:@"  预下单成功!  "] show];
                    JieSuanViewController *yuXiaDanView = [[JieSuanViewController alloc]init];
                    yuXiaDanView.dingDanModel = yudingDan;
                    [self.navigationController pushViewController:yuXiaDanView animated:YES];
                }
            }
        }];
        
    }else{
         [[iToast makeText:@"  没有勾选任何产品!  "] show];
    }
}
@end
